//缓存管理类

import 'package:shared_preferences/shared_preferences.dart';

class EcCache {
  SharedPreferences prefs;

  EcCache._() {
    init();
  }

  static EcCache _instance;

  EcCache._pre(SharedPreferences prefs) {
    this.prefs = prefs;
  }

  ///预初始化，防止在使用get时，prefs还未完成初始化
  static Future<EcCache> preInit() async {
    if (_instance == null) {
      var prefs = await SharedPreferences.getInstance();
      _instance = EcCache._pre(prefs);
    } else {
      var prefs = await SharedPreferences.getInstance();
      _instance = EcCache._pre(prefs);
    }
    return _instance;
  }

  static EcCache getInstance() {
    if (_instance == null) {
      _instance = EcCache._();
    }
    return _instance;
  }

  void init() async {
    if (prefs == null) {
      prefs = await SharedPreferences.getInstance();
    }
  }

  setString(String key, String value) {
    prefs?.setString(key, value);
  }

  setDouble(String key, double value) {
    prefs?.setDouble(key, value);
  }

  setInt(String key, int value) {
    prefs?.setInt(key, value);
  }

  setBool(String key, bool value) {
    prefs?.setBool(key, value);
  }

  setStringList(String key, List<String> value) {
    prefs?.setStringList(key, value);
  }

  remove(String key) {
    prefs?.remove(key);
  }

  T get<T>(String key) {
    var result = prefs?.get(key);
    if (result != null) {
      return result as T;
    }
    return null;
  }

  String getString(String key) {
    var keys = prefs.getKeys();
    if (!keys.contains(key)) return "";
    return prefs.getString(key);
  }

  bool getBool(String key) {
    var keys = prefs.getKeys();
    if (!keys.contains(key)) return false;
    return prefs.getBool(key);
  }

  int getInt(String key) {
    var keys = prefs.getKeys();
    if (!keys.contains(key)) return 0;
    return prefs.getInt(key);
  }



  clear() {
    prefs.getKeys().forEach((element) {
      prefs.remove(element);
    });
    print('-------清除缓存');
    prefs?.clear();
  }
}
